﻿
using System;
using System.Collections.Generic;
using Family.Core.Model;
using NHibernate;
using NHibernate.Criterion;
using NHibernate.LambdaExtensions;
using NHibernate.SqlCommand;
using NHOrder = NHibernate.Criterion.Order;

namespace Family.Data.DBRepositories
{
    public class ProductRepository : Repository<Product>
    {
        private Product p = null;
        private Category c = null;

        public ProductRepository(ISession session) : base(session) { }

        public override void SaveOrUpdate(Product entity)
        {
            var product = GetByName(entity.Name);
            
            if (product == null) 
            {
                session.SaveOrUpdate(entity);
            }
        }
        
        public virtual Product GetByName(string name)
        {
            var criteria = session.CreateCriteria(typeof (Product), () => p)
                .Add<Product>(x => x.Name == name);

            var result = criteria.UniqueResult();

            return result == null ? null : (Product)result;
        }

        public virtual IList<Product> GetProductsByCategoryId(Int32 categoryId)
        {
            var criteria = session.CreateCriteria(typeof (Product), () => p)
                .AddOrder<Product>(x => x.Name, NHOrder.Asc)
                .CreateCriteria(() => p.Category, () => c, JoinType.InnerJoin)
                .Add<Category>(x => x.Id == categoryId);

            return criteria.List<Product>();
        }

        public virtual IList<Product> GetProductsByCategoryIdWithMask(Int32 categoryId, String mask)
        {
            var criteria = session.CreateCriteria(typeof (Product), () => p)
                .Add(SqlExpression.Like<Product>(x => x.Name, mask, MatchMode.Start))
                .AddOrder<Product>(x => x.Name, NHOrder.Asc)
                .CreateCriteria(() => p.Category, () => c, JoinType.InnerJoin)
                .Add<Category>(x => x.Id == categoryId);

            return criteria.List<Product>();
        }
    }
}
